<template>
    <div class="achievement-list-page">
        <el-card shadow="never" class="mt-4">
            <div class="mt-3">
                账号剩余配额: {{ user.expiry_time | restDayFilter(tomorrowDateTimestamp) }} 天
            </div>
            <el-form :inline="true" class="mt-5">
                <el-form-item label="账号配额">
                    <el-select
                        v-model="renew_form.account_application_id"
                        clearable>
                        <el-option
                            v-for="item in applicationOptions"
                            :key="item.id"
                            :label="`激活1个账号配额。（激活后还有${item.count - item.used_count - 1} 个，
                            每个可用${item.duration}天的账号配额 ）`"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-button type="primary" @click="onRenew">激活</el-button>
            </el-form>
            <div class="mt-5" v-loading="loading">
                <span>账号配额使用记录</span>
                <el-table :data="data" class="mt-3">
                    <el-table-column type="index"
                    :index="indexMethod"
                    align="center"
                    label="序号"
                    width="100"/>
                    <el-table-column label="配额天数" prop="duration"></el-table-column>
                    <el-table-column label="类型">
                        <template slot-scope="{row}">
                            {{ row.type | typeFilter }}
                        </template>
                    </el-table-column>
                    <el-table-column label="使用时间">
                        <template slot-scope="{row}">
                            {{ formatTime(row.created_at, '') }}
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div v-if="totalElements > 0" class="footer">
                <pagination
                ref="pagination"
                :currentPage="form.page"
                :pageSize="form.size"
                :handleCurrentChange="onCurrentChange"
                :handlePageSizeChange="onPageSizeChange"
                :totalElements="totalElements"
                ></pagination>
            </div>
        </el-card>
    </div>
</template>

<script>
import Pagination from '../../components/base/Pagination';
import TimeFormats from '../../helpers/TimeFormats';
import IndexNumber from '../../helpers/IndexNumber';

export default {
    components: {
        Pagination,
    },
    mixins: [require('../../mixins/CacheQuery').default],
    data() {
        return {
            loading: false,
            data: [],
            form: {
                page: 1,
                size: 50,
                userId: this.$route.params.id,
            },
            totalElements: 0,
            renew_form: {
                account_application_id: '',
            },
            applicationOptions: [],
            user: '',
            // 当前日期零时零分时间戳
            dateTimestamp: '',
            // 明日日期零时零分时间戳
            tomorrowDateTimestamp: '',
        };
    },
    filters: {
        usedDayFilter: function (activeTime, expiryTime, dateTimestamp) {
            if (activeTime > 0 && expiryTime > 0) {
                if (dateTimestamp > expiryTime) {
                    return (dateTimestamp - expiryTime) / 86400;
                }
                return (dateTimestamp - activeTime) / 86400;
            }
            return '';
        },
        restDayFilter: function (expiryTime, tomorrowDateTimestamp) {
            if (expiryTime > 0) {
                if (tomorrowDateTimestamp < expiryTime) {
                    return Math.floor((expiryTime - tomorrowDateTimestamp) / 86400);
                }
            }
            return 0;
        },
        typeFilter: function (value) {
            if (!value) return '';
            const options = ['开通账号', '账号续费'];
            return options[(value - 1)];
        },
    },
    methods: {
        initDateTimestamp() {
            const now = new Date();
            const today = now.toLocaleDateString().split('/').join('-');
            const date = new Date(today);
            this.dateTimestamp = date.getTime() / 1000;
            this.tomorrowDateTimestamp = this.dateTimestamp + 86400;
        },
        formatTime(timestamp, format) {
            return timestamp ? new TimeFormats().convertTime(format, timestamp) : '';
        },
        isCompanyAccount() {
            return this.$store.state.my.company_id > 0;
        },
        onResetFilters() {
            this.$refs.form.resetFields();
        },
        onCurrentChange(val) {
            this.form.page = val;
            this.fetchData();
        },
        onPageSizeChange(val) {
            this.form.size = val;
            this.form.page = 1;
            this.fetchData();
        },
        fetchData() {
            this.loading = true;
            API.get('account/consume', {params: this.form}).then((res) => {
                this.data = res.content;
                this.totalElements = res.pagination.total;
            }).finally(() => {
                this.loading = false;
            });
        },
        onRenew() {
            if (!this.renew_form.account_application_id) {
                $ele.$message.error('请选择一个账号配额');
                return;
            }

            const accountAppId = this.renew_form.account_application_id;
            const data = this.applicationOptions.filter(option => option.id === accountAppId)[0];
            const msg = `是否确定为此员工账号新增配额 ${data.duration} 天`;
            $ele.$confirm(msg, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.renew_form.user_id = this.user.id;
                this.renew_form.company_id = this.user.company_id;
                API.post('user/renew_account', this.renew_form).then(() => {
                    this.$router.push({
                        name: 'UserManage',
                    });
                }).catch(err => {
                    $ele.$message.error(err.message);
                });
            }).catch(() => { });
        },
        fetchApplicationData() {
            API.get('account/application/list').then((res) => {
                this.applicationOptions = res.filter(option => option.count > option.used_count);
            });
        },
        fetchUser() {
            API.get(`user/${this.$route.params.id}`).then((res) => {
                this.user = res;
            });
        },
        indexMethod(index) {
            return new IndexNumber()
                .getIndex(this.totalElements, this.form.page, this.form.size, index);
        },
    },
    mounted() {
        this.initDateTimestamp();
        this.fetchApplicationData();
        this.fetchUser();
        this.fetchData();
    },
};
</script>

<style lang="scss">
.achievement-list-page {
    .filter {
        .input-width {
            max-width: 200px;
        }
    }
    .logo {
        width: 60px;
        height: 60px;
    }
    .footer {
        height: 44px;
        background: #f7f7f7;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding-left: 20px;
        padding-right: 20px;
    }
    .image-slot {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        background: #f5f7fa;
        color: #909399;
    }
}
</style>
